/**
 * 本地使用http-proxy-middleware搭建反向代理服务器，
 * 与使用webpack-dev-server效果相同
 * 1、启动：nodemon ./src/server/server.js
 */

const express = require('express');
const webpack = require('webpack');
const WebpackDevMiddleware = require('webpack-dev-middleware');
const { createProxyMiddleware } = require('http-proxy-middleware');

const app = express();

// 获取配置文件
const config = require('../../webpack.config.js');
// 打包（当webpack传入一个webpack.config.js的配置文件时编译打包）
const compiler = webpack(config);
// 将编译后文件通过webpack-dev-middleware包装为中间件被app.use加载使用
app.use(WebpackDevMiddleware(compiler));

// 设置代理服务器(相当于devServer中的proxy)
const proxy = createProxyMiddleware({
  target: 'https://api.github.com',
  changeOrigin: true,
  pathRewrite: { '^/api': '' }
})
app.use('/api', proxy);

// 启动服务器，监听端口3000
app.listen(3000, () => {
  console.log('server is running at http://localhost:3000');
})
